<template>
  <div class="supplier-and-contract">
    <div class="block">
      <header>
        <h2 class="required">
          供应商选择
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item label="供应商">
            <el-select
              v-model="supplier_id"
              placeholder="请选择"
              @change="onChangeSupplier"
            >
              <el-option
                v-for="item in rows_supplies"
                :key="item.vendorCode"
                :label="item.vendorName"
                :value="item.vendorCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block select-contract-part">
      <header>
        <h2 class="required">
          授权合同选择
        </h2>
      </header>
      <section class="select">
        <el-radio-group
          v-model="contract_id"
          class="w100p"
          @change="onChangeContract"
        >
          <el-editable
            v-loading="contractTableLoading"
            :need-pagination="true"
            :columns="COLUMNS_CONTRACT"
            :payload="payload_contracts"
            height="250"
            @reload="onLoadData"
          >
            <template #default-checkbox="{ row }">
              <el-radio
                :label="row.contractUnitId"
                :disabled="
                  (storaged.supplier_id === '1440' || supplier_id === '1440') &&
                    (row.vendorCode === 'SHYYLQ' || row.vendorCode === 'SJSNKY')
                "
              >
                {{ '' }}
              </el-radio>
            </template>
          </el-editable>
        </el-radio-group>
      </section>
    </div>
    <div class="block">
      <header>
        <h2 class="required">
          订单类型
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <el-select
              v-if="order_type_ops.length"
              v-model="ordertype"
              placeholder="请选择"
              :disabled="!supplier_id"
              @change="onChangeOrderType"
            >
              <el-option
                v-for="item in order_type_ops"
                :key="item.orderTypeId"
                :label="item.orderTypeName"
                :value="item.orderTypeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <el-dialog
      title="更换供应商"
      :visible.sync="dialogVisible.supplier"
      width="30%"
      :before-close="handleCloseSupplierDialog"
    >
      <span>更换供应商后，对应的采购产品、订单类型都会清空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="supplierDialogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="更换合同"
      :visible.sync="dialogVisible.contract"
      width="30%"
      :before-close="handleCloseContractDialog"
    >
      <span>更换合同后，对应的采购产品、订单类型都会清空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contractDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="contractDialogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="更换订单类型"
      :visible.sync="dialogVisible.orderType"
      width="30%"
      :before-close="orderTypeDialogRefuse"
    >
      <span>更换订单类型后，对应的采购产品会清空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderTypeDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="orderTypeDialogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import { getOrderTypeWholesale } from '@api/m_mall_web_v1.js';
import * as CONSTS from './supplier-and-contract.const';

export default {
  components: {
    ElEditable
  },
  inject: ['apiMMallWeb'],
  props: {
    supplierId: {
      type: String,
      default: ''
    },
    orderTypeId: {
      type: String,
      default: ''
    },
    orderTypeDDBM: {
      type: String,
      default: ''
    },
    contractId: {
      type: String,
      default: ''
    },
    busModel: {
      type: String,
      default: ''
    },
    products: {
      type: Array,
      default: () => []
    },
    onsignOrderType: Boolean,
    orderType: {
      type: String,
      default: ''
    },
    isFirstMount: Boolean
  },
  data() {
    return {
      ...CONSTS,
      table_query: {},
      order_type_ops: [],
      rows_supplies: [], // 产品线列表数据
      payload_contracts: {}, // 产品线数据
      supplier_id: '',
      supplier_code: '', // 判断单选框是否禁用
      ordertype: '',
      contract_id: '',
      full_data: {
        vendorName: '',
        vendorCode: '',
        contractName: '',
        contractCode: '',
        originalFactoryName: '',
        originalFactoryCode: '',
        productLineName: '',
        productLineCode: ''
      },
      storaged: {
        supplier_id: '',
        contract_id: '',
        orderType: ''
      },
      dialogVisible: {
        orderType: false,
        supplier: false,
        contract: false
      },
      contractTableLoading: false,
      selectOrderType: ''
    };
  },
  computed: {
    // 判断是否存在产品信息或订单类型，如果存在则为true，用于在切换供应商或合同时提示
    isNeedAlert() {
      return this.onsignOrderType
        ? this.products.length > 0
        : this.products.length > 0 || this.orderType;
      // if(this.onsignOrderType) {
      //   if(this.products.length > 0) {
      //     return true;
      //   }
      // } else if (this.products.length > 0 || this.orderType) {
      //   return true;
      // }
      // return false;
    }
  },
  watch: {
    supplierId: {
      handler(val) {
        if (val !== '') {
          this.supplier_id = val;
          console.log(this.supplier_id, '233-------');
          this.storaged.supplier_id = val;
          this.onLoadData({ number: 1, size: 20 });
          // 当重新获取合同列表时，手动清空合同绑定的及缓存的值
          // 如果是第一次加载，则不把合同置为空
          // 只要没切换supplierId，或者ContractId就视为第一次加载
          if (!this.isFirstMount) {
            this.contract_id = '';
            this.storaged.contract_id = '';
            this.ordertype = '';
            this.storaged.orderType = '';
            this.full_data.contract = '';
            // 清空相应数据后还要更新
            this.$emit('update:contractId', this.contract_id);
            this.changeOrderType('');
          }
        }
      },
      immediate: true
    },
    orderTypeId: {
      handler(val) {
        this.ordertype = val;
        this.storaged.orderType = val;
      },
      immediate: true
    },
    contractId: {
      handler(val) {
        this.contract_id = val;
        this.storaged.contract_id = val;
        // this.storaged.supplier_id = val
      },
      immediate: true
    }
  },
  created() {
    this.orderTypeMap = {};
    this.contractListMap = {};
    this.getSuppliers();
  },
  methods: {
    onGetOrderTypeData(id) {
      this.$axios({
        url: getOrderTypeWholesale,
        method: 'post',
        data: {
          // busModel: this.busModel,
          supplierCode: id,
          page: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data.code === '0') {
          this.order_type_ops = res.data.payload;
          this.order_type_ops.forEach(item => {
            this.orderTypeMap[item.orderTypeId] = item.ddbm;
          });
          if (!this.orderTypeMap[this.ordertype]) {
            this.ordertype = '';
            this.storaged.orderType = '';
            this.$emit('update:orderTypeId', '');
          }
        }
      });
    },
    async getSuppliers() {
      const supplies = await this.apiMMallWeb.SupplierOrderV1ApiPOST({
        query: { busModel: this.busModel, page: 1, size: 1000 }
      });
      this.rows_supplies = supplies.content || [];
    },
    // 由于合同特殊性，要特别前端判断唯一性，创建contractUnitId
    getContractUnitId(item) {
      const contractUnitId = `${item.supplierCode ||
        ''}${item.productLineCode || ''}${item.businessModelCode ||
        ''}${item.marketCode || ''}`;
      this.contractListMap[contractUnitId] = item.vendorCode;
      return contractUnitId;
    },
    async onLoadData(pager) {
      if (!this.supplier_id) {
        this.$message.error('请选择供应商');
        return;
      }
      this.contractTableLoading = true;
      const contracts = await this.apiMMallWeb
        .ContractOrderV1ApiPOST({
          query: {
            page: pager.number,
            pageSize: pager.size,
            supplierCode: this.supplier_id,
            busModel: this.busModel
          }
        })
        .finally(() => {
          this.contractTableLoading = false;
        });
      this.payload_contracts = contracts || [];
      this.payload_contracts.content.forEach(item => {
        this.$set(item, 'contractUnitId', this.getContractUnitId(item));
      });
      if (this.contract_id) {
        this.onGetOrderTypeData(this.contractListMap[this.contract_id]);
      }
      const contract = this.payload_contracts.content.find(
        item => item.contractUnitId === this.contract_id
      );
      if (contract !== undefined) {
        const supplier = this.rows_supplies.find(
          item => item.vendorCode === this.supplier_id
        );
        this.full_data.vendorName = supplier.vendorName || '';
        this.full_data.vendorCode = supplier.vendorCode || '';
        Object.assign(this.full_data, contract);
        this.$emit('change', this.full_data);
      }
    },
    supplierCommonProgress(supplierId) {
      // 走剩下的逻辑
      this.$emit('update:supplierId', supplierId);
      const suppliy = this.rows_supplies.find(
        item => item.vendorCode === supplierId
      );
      // 为了上一层的取值，这里额外再赋值一下
      this.full_data.suppliy = suppliy;
      Object.assign(this.full_data, suppliy);
      // 这里通过emit给上级传递数据，触发watch，加载数据
      this.$emit('update:isFirstMount', false);
      this.$emit('change', this.full_data);
    },
    onChangeSupplier(value) {
      this.supplier_code = value;
      if (this.isNeedAlert) {
        this.dialogVisible.supplier = true;
      } else {
        this.storaged.supplier_id = value;
        this.supplierCommonProgress(value);
      }
      // // 如果存在暂存数据，那要显示弹窗，并给当前选中数据赋值
      // if (this.storaged.supplier_id) {
      //   this.dialogVisible.supplier = true;
      // } else {
      //   this.storaged.supplier_id = value;
      //   this.supplierCommonProgress(value);
      // }
    },
    supplierDialogConfirm() {
      this.dialogVisible.supplier = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.supplier_id = this.supplier_id;
      // 加这个字段，是因为无论取消还是确定都要更新
      // this.needClearSupplier = true;
      this.supplierCommonProgress(this.supplier_id);
    },
    supplierDialogRefuse() {
      this.dialogVisible.supplier = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      this.supplier_id = this.storaged.supplier_id;
      // this.needClearSupplier = false;
      // this.supplierCommonProgress(this.supplier_id);
    },
    handleCloseSupplierDialog() {
      this.supplierDialogRefuse();
    },
    contractCommonProgress(contractId) {
      this.$emit('update:contractId', contractId);
      this.storaged.contract_id = contractId;
      const contract = this.payload_contracts.content.find(
        item => item.contractUnitId === contractId
      );
      // 为了上一层的取值，这里额外再赋值一下
      this.$emit('update:isFirstMount', false);
      this.full_data.contract = contract;
      this.$emit('change', this.full_data);
    },
    onChangeContract(contractId) {
      this.onGetOrderTypeData(this.contractListMap[contractId]);
      if (this.isNeedAlert) {
        this.dialogVisible.contract = true;
      } else {
        this.storaged.contract_id = contractId;
        this.contractCommonProgress(contractId);
      }
    },
    contractDialogConfirm() {
      this.dialogVisible.contract = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.contract_id = this.contract_id;
      this.contractCommonProgress(this.contract_id);
    },
    contractDialogRefuse() {
      this.dialogVisible.contract = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      this.contract_id = this.storaged.contract_id;
      // this.contractCommonProgress(this.contract_id);
    },
    onChangeOrderType(value) {
      if (this.storaged.orderType && this.products.length) {
        this.dialogVisible.orderType = true;
      } else {
        this.changeOrderType(value);
      }
      this.ordertype = value;
    },
    orderTypeDialogConfirm() {
      this.storaged.orderType = this.ordertype;
      this.$emit('update:isFirstMount', false);
      // this.full_data.contract = contract;
      this.$emit('change', this.full_data);
      this.changeOrderType(this.ordertype);
      this.dialogVisible.orderType = false;
    },
    orderTypeDialogRefuse() {
      this.ordertype = this.storaged.orderType;
      this.dialogVisible.orderType = false;
    },
    changeOrderType(value) {
      this.$emit('update:orderTypeId', value);
      this.$emit('update:orderTypeDDBM', this.orderTypeMap[value] || '');
    },
    handleCloseContractDialog() {
      this.contractDialogRefuse();
    }
  }
};
</script>

<style lang="less">
.w100p {
  width: 100%;
}
.supplier-and-contract {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  .select {
    height: 250px;
  }
}
// .wholesale-add .select-contract-part {
//   height: 280px !important;
// }
</style>
